package day1;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test1 {
    static Jedis j=new Jedis("192.168.188.100",6379);

    @Test
    public void m1(){
        j.set("address","南京");
        System.out.println(j.get("address"));
        j.incrBy("age",10);
        System.out.println(j.keys("*"));
        Map<String,String>m=new HashMap<>();
        m.put("a1","11");
        m.put("a2","22");
        j.hmset("users",m);
        System.out.println(j.hgetAll("users"));
    }

    @Test
    public void t()throws Exception{
        j.set("money","960");//可用额度
        j.set("debt","40");

        int consume=20;
        j.watch("money");//开启乐观锁，监听money

        Thread.sleep(10000);
        int money=Integer.parseInt(j.get("money"));

        if(money<consume){
            j.unwatch();
            System.out.println("信用卡额度不够");
            return;
        }

        System.out.println("---------开启事务----------");
        Transaction t=j.multi();
        t.incrBy("debt",consume);
        t.decrBy("money",consume);
        //集合中存放的是事务中执行的结果
        List list=t.exec();
        if (list==null){
            System.out.println("事务失败，money被其他线程修改。");
            j.unwatch();
        }
        System.out.println("事务执行结束，当前余额为："+j.get("money")+",欠账："+j.get("debt"));
    }

    @Test
    public void master_slave(){
        Jedis master=new Jedis("192.168.188.100",6379);
        Jedis slave=new Jedis("192.168.188.100",6380);
        slave.slaveof("192.168.188.100",6379);

        master.set("driver","com.mysql.driver");

        System.out.println(slave.get("driver"));
    }


}
